#include "countdown.h"

#include <QPainter>

CountDown::CountDown(QWidget *parent) : QWidget(parent)
{
    setFixedSize(70, 70); //设置当前窗口大小和闹钟大小一致
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, [=]()
    {
        m_count--;
        if(m_count < 10 && m_count > 0) //开始显示闹钟
        {
            m_clock.load(":/images/clock.png");
            //加载闹钟上的数字   m_count*(30+10) 从9开始侠显示  30, 42是数字的宽度和高度  scaled(20, 30) 缩放
            m_number = QPixmap(":/images/number.png").copy(m_count*(30+10), 0, 30, 42).scaled(20, 30);
            if(m_count == 5) //播放提示音乐
            {
                emit notMuchTime();
            }
        }
        else if(m_count <= 0)
        {
            m_clock = QPixmap(); //置空
            m_number = QPixmap();
            m_timer->stop();
            emit timeout(); //通知主界面
        }
        update();  //刷新当前窗口
    });
}

void CountDown::showCountDown()
{
    m_count = 15;
    m_timer->start(1000); //定时一秒，1秒后发送timeout信号
}

void CountDown::stopCountDown()
{
    m_timer->stop(); //关掉定时器
    m_clock = QPixmap(); //隐藏时钟
    m_number = QPixmap(); //隐藏数字
    update(); //重新绘制窗口
}

void CountDown::paintEvent(QPaintEvent *ev)
{
    Q_UNUSED(ev)
    QPainter p(this);
    p.drawPixmap(rect(), m_clock); //画闹钟
    p.drawPixmap(24, 24, m_number.width(),m_number.height(), m_number); //画闹钟上的数字
}
